// GLOBAL VARIABLES
var width = 1000,
  height = 600,
  gLoop,
  c = document.getElementById('canvas'),
  ctx = c.getContext('2d'),
  player = new Player("Spaceship_smaller.png", 25, 50, 0,0, ctx, 1),
  howManyCircles = 15

// Initialize the game
var init = function () 
{
    player.setPosition(((width - player.width) / 2), ((height - player.height) / 2));
    c.width = width;
    c.height = height;

    c.onmousedown = myMouseDown;

    circles = [];

    for (var i = 0; i < howManyCircles; i++)
        circles.push([Math.random() * width, Math.random() * height, Math.random() * 100, Math.random() / 2]);

    GameLoop(); // initiate the gameloop
};

init();

// FUNCTIONS

// Clear the canvas
function clear() 
{
    ctx.fillStyle = '#000000';
    ctx.clearRect(0, 0, width, height);
    ctx.beginPath();
    ctx.rect(0, 0, width, height);
    ctx.closePath();
    ctx.fill();
}

// Create the stars!
function DrawCircles()
{
  for (var i = 0; i < howManyCircles; i++) {
    ctx.fillStyle = 'rgba(255, 255, 255, 255)';
    ctx.beginPath();
    ctx.arc(circles[i][0], circles[i][1], 2, 2, Math.PI * 2, true);
    ctx.closePath();
    ctx.fill();
  }
};

// Move the background
function MoveCircles(e)
{
  for (var i = 0; i < howManyCircles; i++) {
    if (circles[i][1] - circles[i][2] > height) {
      circles[i][0] = Math.random() * width;
      circles[i][2] = Math.random() * 100;
      circles[i][1] = 0 - circles[i][2];
      circles[i][3] = Math.random() / 2;
    }
    else {
      circles[i][1] += e;
    }
  }
};

// This is a recursive function. It calls itself, so in effect is an endless loop...
function GameLoop()
{
  clear();
  MoveCircles(5);
  DrawCircles();
  player.draw();
  gLoop = setTimeout(GameLoop, 1000 / 50);
}

// Mousehandler for downevent
function myMouseDown(e)
{
    var mouseX = e.pageX - this.offsetLeft;
    var mouseY = e.pageY - this.offsetTop;
    player.setPosition(mouseX, mouseY);
}


